package com.example.leo.mycharmingstudent.a0903;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import com.example.leo.mycharmingstudent.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

public class NetWorkActivity extends AppCompatActivity {

    private static final String TAG = "NetWorkActivity";

    //显示get请求回来的结果，json字符串
    private TextView tvGotContent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_net_work);

        findViews();
        initData();
        initEvent();
    }

    private void findViews() {
        tvGotContent = findViewById(R.id.tv_get_content_activity_net_work);
    }

    private void initData() {
        //注意，此处在主线程中进行网络请求
        /**
         * Android中不可以在主线程中进行网络操作
         * NetworkOnMainThreadException
         * 为什么Android中不可以在主线程中进行网络操作呢？
         * 1.网络请求是阻塞式的
         * 2.主线程中，如果主线程被阻塞超过10s，会提示无响应。
         *
         * 我都已经按照要求，在子线程中进行网络请求了，还给我报错，为啥？
         * java.lang.SecurityException: Permission denied (missing INTERNET permission?)
         * 因为，没有申请网络权限。
         */
        /*new Thread(new Runnable() {
            @Override
            public void run() {
                final String result = requestDataByGet("https://wanandroid.com/wxarticle/chapters/json");
                *//*
                子线程中不可以进行UI操作，UI操作必须在主线程中进行
                runOnUiThread方法传入Runnable对象，
                Runnable对象里面的run()会在主线程中进行
                 *//*
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tvGotContent.setText(result);
                    }
                });
            }
        }).start();*/
        new Thread(new Runnable() {
            @Override
            public void run() {
                final String result = requestDataByPost("https://www.wanandroid.com/user/register");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        /*
                         Json解析流程（JsonObject） ：
                         1.创建JsonObject
                         2.调用相应的方法获取数据
                         */
                        try {
                            JSONObject jsonObject = new JSONObject(result);
                            JSONArray data = jsonObject.optJSONArray("data");
                            String errorCode = jsonObject.optString("errorCode");
                            String errorMsg = jsonObject.optString("errorMsg");
                            String format = String.format("data:%s-errorCode:%s-errorMsg:%s",
                                    String.valueOf(data), errorCode, errorMsg);
                            tvGotContent.setText(format);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        }).start();
    }

    private void initEvent() {

    }

    private String requestDataByGet(String urlString) {
        String result = null;
        try {
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(30000);
            connection.setRequestMethod("GET");  // GET POST
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Charset", "UTF-8");
            connection.setRequestProperty("Accept-Charset", "UTF-8");
            connection.connect();
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = connection.getInputStream();
                result = streamToString(inputStream);
            } else {
                String responseMessage = connection.getResponseMessage();
                Log.e(TAG, "requestDataByPost: " + responseMessage);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 将输入流转换成字符串
     *
     * @param is 从网络获取的输入流
     * @return 字符串
     */
    public String streamToString(InputStream is) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            baos.close();
            is.close();
            byte[] byteArray = baos.toByteArray();
            return new String(byteArray);
        } catch (Exception e) {
            Log.e(TAG, e.toString());
            return null;
        }
    }

    private String requestDataByPost(String urlString) {
        String result = null;
        try {
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(30000);
            connection.setRequestMethod("POST");

            // 设置运行输入,输出:
            connection.setDoOutput(true);
            connection.setDoInput(true);
            // Post方式不能缓存,需手动设置为false
            connection.setUseCaches(false);
            connection.connect();

            // 我们请求的数据:
            String data = "username=" + URLEncoder.encode("wangxiaoer", "UTF-8")
                    + "&password=" + URLEncoder.encode("123456", "UTF-8")
                    + "&repassword=" + URLEncoder.encode("123456", "UTF-8");
            // 获取输出流
            OutputStream out = connection.getOutputStream();
            out.write(data.getBytes());
            out.flush();
            out.close();

            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = connection.getInputStream();
                Reader reader = new InputStreamReader(inputStream, "UTF-8");
                char[] buffer = new char[1024];
                reader.read(buffer);
                result = new String(buffer);
                reader.close();
            } else {
                String responseMessage = connection.getResponseMessage();
                Log.e(TAG, "requestDataByPost: " + responseMessage);
            }

            final String finalResult = result;

            connection.disconnect();
            return result;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
